#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<cstring>
#include<string>
using namespace std;
#define _MAXLINE 128
#define _MAXCHAR 256

int help(){
    cout << "Usage:" << endl ;
    cout << " ledit [mode] [line] [filename] [(line_value)]" << endl ;
    cout << "\nMode:" << endl ;
    cout << "   -h or --help         print the help text;" << endl ;
    cout << "   -r or --read         read a line form [filename], the line number is [line];" << endl ;
    cout << "   -w or --write         write [line_value] to the [line]th line of [filename];" << endl ;
    cout << "\nFor example:" << endl ;
    cout << "For read a line form file: \n        ledit -r 4 example.txt" << endl ;
    cout << "For write a line to file: \n        ledit -w 4 example.txt hello!" << endl ;
    cout << "\n@ We are very sorry that this program only support text file with " << _MAXLINE << " line max, and " << _MAXCHAR << " char each line." << endl;
    return 0;
}         //help infomation;

int main(int argc , char *argv[]){
    int n = 0;
    if(argc>=4){
        n = atoi(argv[2]) ;
        if( n>_MAXLINE || n<0 ){
            cout << "This program only support text with " << _MAXLINE << " line max" << endl;
        }
    }       //check for line;
    int m = 0;
    if( (argc <= 3) || (!strcmp(argv[1],"-h")) || (!strcmp(argv[1],"--help")) ){
        help();
    }           //if got wrong argv, print help;

    else{
        ifstream filenamei(argv[3], std::ios::in);
        if( filenamei==NULL ){
            filenamei.close();
            help();
            return 0;
        }       //if no filename, exit;

        char textline[_MAXCHAR][_MAXLINE];
        int i = 1 ;
        string outp[_MAXLINE] ;    //string for del \n;
        if(!strcmp(argv[1],"-r")||!strcmp(argv[1],"--read")){
            while(!filenamei.eof()) {
                filenamei.getline(textline[i],256) ;
                outp[i] = textline[i] ;
                i++ ;
            } ;
            cout << outp[n] << endl ;
        }       //funtion for read file;

        i = 1;filenamei.clear();        //get ready for write;
        while(!filenamei.eof()) {
            filenamei.getline(textline[i],256) ;
            outp[i] = textline[i] ;
            i++ ;
        }       //read file for write;
        filenamei.close();

        if(!strcmp(argv[1],"-w")||!strcmp(argv[1],"--write")){
            ofstream filenameo(argv[3], ios::trunc);
            outp[n] = argv[4];      //change the line;
            m = i-1;
            i = 1;
            filenameo.clear();
            while(i <= m) {
                if(i < m){
                    filenameo << outp[i] << endl;
                }
                if(i == m){
                    filenameo << outp[i];
                }
                i++;
            }           //write to file;
            filenameo.close();
        }
    }

  return 0;
  }

